using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Web.Security;
using Animoso.Domain;
using Animoso.Domain.Data;

namespace Animoso.Web.Controllers
{
    public class AccountController : ApplicationController
    {
        private IRepository<User> _userRepository;

        public AccountController(IRepository<User> userRepository)
        {
            _userRepository = userRepository;
        }

        public ActionResult Index()
        {
            return View(_userRepository.GetAll());
        }

        public JsonResult Delete(int userId)
        {
            Domain.User user = _userRepository.GetById(userId);
            _userRepository.Delete(user);

            return Json(true, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Edit(int id)
        {
            Domain.User user = _userRepository.GetById(id);
            return View(user);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(int id, string Name, string Password, string ConfirmPassword)
        {
           Domain.User user = _userRepository.GetById(id);
            
           if(!string.IsNullOrEmpty(Password) || string.IsNullOrEmpty(ConfirmPassword)) 
           {
               if(Password != ConfirmPassword)
               {
                   ModelState.AddModelError("Password", "Bevestigd Wachtwoord moet hetzelfde zijn als het wachtwoord");
                   ModelState.AddModelError("ConfirmPassword", "Bevestigd Wachtwoord moet hetzelfde zijn als het wachtwoord");
               }
           }
            if(string.IsNullOrEmpty(Name))
            {
                ModelState.AddModelError("Name", "Je moet een naam invullen");
            }

            if (!ModelState.IsValid)
                return View("Edit", user);

            user.Name = Name;
            user.Password = Password;
            _userRepository.Save(user);

            return RedirectToAction("Index");
        }

        public ActionResult Create()
        {
            Domain.User user = new User();
            _userRepository.Add(user);
            return View("Edit", user);
        }

        public ActionResult Back(int id)
        {
            Domain.User user = _userRepository.GetById(id);
            _userRepository.Delete(user);

            return RedirectToAction("Index");
        }
    }
}
